﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace Marbles.Core.Handlers
{
    public class ProfileImageHandler : HttpHandlerBase, IHttpHandlerBase
    {
        public void ProcessRequest(HttpContext context)
        {
            string userid = string.Empty;
            string id = string.Empty;
            if (context.Request.Params["id"] != null) { id = context.Request.Params["id"]; }
            if (context.Request.Params["uid"] != null) { userid = context.Request.Params["uid"]; }

            if ((string.IsNullOrEmpty(userid)) && (this.CurrentToken != null)) { userid = this.CurrentToken.UserId; }

            if (string.IsNullOrEmpty(id)) { id = userid; }

            if (string.IsNullOrEmpty(id)) { return; }
            if (string.IsNullOrEmpty(userid)) { return; }

            string dirPath = context.Server.MapPath(string.Format("/App_Data/Profiles/{0}", userid));
            foreach (string file in System.IO.Directory.GetFiles(dirPath, userid + ".*"))
            {
                System.IO.FileInfo info = new FileInfo(file);
                Download(context.Response, userid, info.Name);
            }


        }

        public void Download(HttpResponse response, string userid, string filename)
        {
            string dirPath = string.Format("/App_Data/Profiles/{0}/{1}", userid, filename);
            response.ContentType = "image/";
            response.AddHeader("content-disposition", string.Format("inline;filename={0}", filename));

            FileStream fs = new FileStream(HttpContext.Current.Server.MapPath(dirPath), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            byte[] buffer = new Byte[10000];
            int length = 1;
            long dataToRead = 0;

            //dataToRead = iStream.Length;

            while (length > 0)
            {
                if (response.IsClientConnected)
                {
                    length = fs.Read(buffer, 0, 10000);
                    response.OutputStream.Write(buffer, 0, length);
                    response.Flush();
                    buffer = new Byte[10000];
                    dataToRead = dataToRead - length;
                }
                else
                {
                    dataToRead = -1;
                }
            }

            fs.Close();
            response.Flush();
        }


        public string Verbs
        {
            get { return "GET"; }
        }

        public bool Validate
        {
            get { return false; }
        }

        public string Path
        {
            get { return "ProfileImage.axd"; }
        }

        public string Name
        {
            get { return this.GetType().Name; }
        }

        public bool IsReusable
        {
            get { return false; }
        }
    }
}